<template>
  <div>
    <h2>设备属性元数据配置</h2>
    <div class="table-toolbar">
      <el-button type="primary" @click="addPropertyDialogVisible = true"
        >添加
      </el-button>
      <el-button type="warning" @click="startEdit">修改</el-button>
      <!--      <el-button type="success" @click="saveProperties">保存</el-button>-->
      <el-button type="danger" @click="deleteSelectedProperties"
        >删除
      </el-button>
    </div>
    <el-table
      ref="propertyTable"
      :data="propertyList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column prop="model" label="模型" />
      <el-table-column prop="property" label="属性" />
      <el-table-column prop="displayName" label="显示名称" />
      <el-table-column prop="dataType" label="数据类型" />
      <el-table-column prop="max" label="最大值" />
      <el-table-column prop="min" label="最小值" />
      <el-table-column prop="precision" label="精度" />
      <el-table-column prop="unit" label="单位" />
      <el-table-column prop="defaultValue" label="默认值" />
      <el-table-column prop="enumValues" label="枚举值" />
      <el-table-column prop="required" label="必需" />
    </el-table>
    <el-dialog title="添加属性" v-model="addPropertyDialogVisible" width="50%">
      <AddPropertyForm
        @submit="addProperty"
        @AddPropertyForm_close="addPropertyDialogVisible = false"
      />
    </el-dialog>
    <el-dialog title="修改属性" v-model="editPropertyDialogVisible" width="50%">
      <AddPropertyForm
        :property="selectedProperties[0]"
        @submit="updateProperty"
        @AddPropertyForm_close="editPropertyDialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from "vue";

import AddPropertyForm from "./components/AddPropertyForm.vue";
import {
  DeviceProperty,
  getDeviceProperties,
  addDeviceProperties,
  updateDeviceProperties,
  deleteDeviceProperties
} from "@/api/deviceApi";
import { ElMessage, ElMessageBox } from "element-plus";

export default defineComponent({
  components: {
    AddPropertyForm
  },
  setup() {
    const propertyTable = ref(null);
    const propertyList = ref<DeviceProperty[]>([]);
    const addPropertyDialogVisible = ref(false);
    const selectedProperties = ref<DeviceProperty[]>([]);

    const handleSelectionChange = (val: DeviceProperty[]) => {
      selectedProperties.value = val;
    };

    const editPropertyDialogVisible = ref(false);

    const startEdit = () => {
      if (selectedProperties.value.length !== 1) {
        // Show warning if not exactly one property is selected
        ElMessage.warning({
          message: "请选择一个属性进行编辑",
          duration: 3000
        });
        return;
      }
      editPropertyDialogVisible.value = true;
    };

    const updateProperty = (p: Partial<DeviceProperty>) => {
      const selectedIndex = propertyList.value.findIndex(
        property => property === selectedProperties.value[0]
      );
      // update property to device
      const updatedProperty = {
        ...selectedProperties.value[selectedIndex],
        ...p
      };
      updateDeviceProperties(updatedProperty)
        .then(() => {
          console.log("Device property updated successfully");
        })
        .catch(error => {
          console.error("Failed to update device property:", error);
        });
      propertyList.value.splice(selectedIndex, 1, updatedProperty);

      editPropertyDialogVisible.value = false;
    };

    const saveProperties = () => {
      // Implement your saving logic here, for example, send the data to the server
      updateDeviceProperties(propertyList.value);
      console.log("Saving properties:", propertyList.value);
    };

    const deleteSelectedProperties = () => {
      if (selectedProperties.value.length === 0) {
        ElMessage.warning("请至少选择一个属性进行删除");
        return;
      }

      ElMessageBox.confirm("确定删除所选属性吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await deleteDeviceProperties(selectedProperties.value);
          propertyList.value = propertyList.value.filter(
            property => !selectedProperties.value.includes(property)
          );
          selectedProperties.value = [];
          ElMessage.success("删除成功");
        })
        .catch(() => {
          ElMessage.info("已取消删除");
        });
    };

    const addProperty = async (property: DeviceProperty) => {
      try {
        const response = await addDeviceProperties(property);

        if (response.errorCode === 0) {
          propertyList.value.push(property);
          addPropertyDialogVisible.value = false;
        } else {
          console.error("Failed to add device property:", response.message);
        }
      } catch (error) {
        console.error("Error adding device property:", error);
      }
    };
    const fetchDeviceProperties = async () => {
      try {
        const response = await getDeviceProperties();
        if (response.errorCode == 0) {
          const list = [];
          for (const model in response.data) {
            for (const p of response.data[model]) {
              p.model = model;
              list.push(p);
            }
          }
          propertyList.value = list;
        } else {
          console.error("Failed to fetch device properties:", response.message);
        }
      } catch (error) {
        console.error("Error fetching device properties:", error);
      }
    };

    onMounted(() => {
      fetchDeviceProperties();
    });
    return {
      propertyTable,
      propertyList,
      addPropertyDialogVisible,
      handleSelectionChange,
      saveProperties,
      deleteSelectedProperties,
      addProperty,
      fetchDeviceProperties,
      editPropertyDialogVisible,
      startEdit,
      updateProperty,
      selectedProperties
    };
  }
});
</script>

<style scoped>
.table-toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}
</style>
